package repository

import (
	"gorm.io/gorm/clause"
	"niu-video/app/model"
	"niu-video/pkg/db"
)

var VideoRepository = newVideoRepository()

func newVideoRepository() *videoRepository {
	return &videoRepository{}
}

type videoRepository struct {
	baseRepository
}

// GetOne 通过 ID 获取用户
func (v *videoRepository) GetOne(id int64) (videoModel model.Video) {
	db.DB.Where("video_id", id).First(&videoModel)
	return
}

func (v *videoRepository) Delete(id int64) {
	db.DB.Model(&model.Video{}).Where("video_id", id).Update("is_delete", true)
	return
}

func (v *videoRepository) Create(video *model.Video) (err error) {
	err = db.DB.Create(video).Error
	return err
}

func (v *videoRepository) UpdateLikeCount(id int64, cnt int64) (videoModel model.Video) {
	db.DB.Where("video_id", id).Update("like_count", cnt)
	return
}

func (v *videoRepository) UpdateCollectionCount(id int64, cnt int64) (videoModel model.Video) {
	db.DB.Where("video_id", id).Update("collection_count", cnt)
	return
}

func (v *videoRepository) Page(page int, pageSize int,
	order clause.OrderByColumn) (list []model.Video, err error) {
	if err := db.DB.
		Order(order).
		Offset((page-1)*pageSize).
		Limit(pageSize).
		Where("is_delete", false).
		Find(&list).Error; err != nil {
		return list, err
	}
	return list, nil
}

// VideoCountByUserId
//
//	@Description: 统计userId的作品数量
//	@receiver v
//	@param userId
//	@return count
func (v *videoRepository) VideoCountByUserId(userId int64) (count int64) {
	db.DB.Model(&model.Video{}).
		Where("user_id = ?", userId).
		Where("is_delete", false).
		Count(&count)
	return
}

func (v *videoRepository) UserVideoList(page int, pageSize int, userId int64) (list []model.Video, err error) {
	if err := db.DB.
		Order(clause.OrderByColumn{
			Column: clause.Column{
				Name: "create_time",
			},
			Desc: true,
		}).
		Offset((page-1)*pageSize).
		Limit(pageSize).
		Where("user_id", userId).
		Where("is_delete", false).
		Find(&list).Error; err != nil {
		return list, err
	}
	return list, nil
}

func (v *videoRepository) Offset(offset int, limit int) (list []model.Video, err error) {
	if err := db.DB.
		Order(clause.OrderByColumn{
			Column: clause.Column{
				Name: "create_time",
			},
			Desc: true,
		}).
		Offset(offset).
		Limit(limit).
		Where("is_delete", false).
		Find(&list).Error; err != nil {
		return list, err
	}
	return list, nil
}

func (v *videoRepository) Random(limit int) (list []model.Video, err error) {
	if err := db.DB.
		Order("RAND()").
		Limit(limit).
		Where("is_delete", false).
		Find(&list).Error; err != nil {
		return list, err
	}
	return list, nil
}

func (v *videoRepository) In(ids []string) (list []model.Video, err error) {
	db.DB.Model(&model.Video{}).
		Where("is_delete", false).
		Where("video_id IN (?)", ids).Find(&list)
	return
}
